#!/bin/bash

# 无线网卡
    # 判断是否有IP，如果有IP代表无线网卡可用

# 无线网卡获取IP失败则判断有线网卡
    # 判断网线是否连接

# 网线是否连通
# 网关是否连通
# DNS是否连通
# 域名是否连通


#脚本退出函数
err_mes()
{
    echo $1
    exit $2
}

#获取网卡的IP地址
get_ip()
{
    [ -z $1 ] && return 1

    ip=$(ifconfig $1)
    [ -z "$ip" ] && return 2

    ip=${ip#*inet addr:}
    [ -z "$ip" ] && return 3

    echo ${ip%% Bcast:*}

    return 0
}

#封装ping命令
my_ping()
{
    [ -z $1 ] && return 1
    [ -z $2 ] && num=1 || num=$2
    ping -c $num $1 &> /dev/null && return 0 || return 1
}

#网关检查
gateway_check()
{
    [ -z $1 ] && return 1
    ip=$1
    ip_gateway=${ip%.*}.1
    echo '准备检查网关...'
    gateway=$(route -n | grep UG | awk '{print $2}')
    if [ -z "$gateway" -o "x$gateway" != "x$ip_gateway" ]; then
        echo '网关未设置, 自动修复网关...'
        route add default gw $ip_gateway
    fi
    my_ping $ip_gateway && return 0 || err_mes "网关连接出现问题，请检查!" 2
}

dns_check()
{
    echo '准备检查DNS...'
    my_ping 223.5.5.5   \
        || err_mes "外网连接不通，请检查路由器或拨号情况!" 2
    my_ping www.baidu.com 2 && return 0
    echo "准备自动修复DNS..."
    echo 'nameserver 8.8.8.8' >> /etc/resolv.conf
    echo 'nameserver 223.5.5.5' >> /etc/resolv.conf
    echo 'nameserver 223.6.6.6' >> /etc/resolv.conf
    my_ping www.baidu.com 2     \
        || err_mes "网络异常, 无法解决!"
}

wlan_check()
{
    [ -z $1 ] && return 1
    gateway_check $1
    dns_check
    echo "网络没有任何问题!"
}

#自动获取IP
enp_dhcp()
{
    [ -z $1 ] && return 1
    eth_name=$1

    echo '准备修复网卡IP地址...'
    dhclient $eth_name
    ip=$(get_ip $eth_name)
    [ -z $ip ] && return 2
}

enp_handle()
{
    mode=$1
    eth_name=$2
    [ -z $mode -o -z $eth_name ] && return 1

    echo "准备检查 $eth_name 有线网卡..."

    if ! mii-tool $eth_name 2> /dev/null      \
            | grep 'link ok' &> /dev/null
    then
        echo "$eth_name 网卡的网线没有插好!"
        [ $mode != "for" ] && exit 2 || return 2
    fi

    ip=$(get_ip $eth_name)
    if [ -z $ip ]; then
        if enp_dhcp $eth_name
        then
            echo "$eth_name 网卡自动获取IP失败!"
            [ $mode != "for" ] && exit 2 || return 2
        fi
    fi

    wlan_check $ip
}

wlan_handle()
{
    mode=$1
    eth_name=$2
    [ -z $mode -o -z $eth_name ] && return 1

    echo "准备检查 $eth_name 无线网卡..."

    ip=$(get_ip $eth_name)
    if [ -z $ip ]; then
        echo "$eth_name 无线网卡未连热点!"
        [ $mode != "for" ] && exit 2 || return 2
    fi

    wlan_check $ip
}

#检查是否使用sudo
[ $UID -ne 0 ]  && err_mes "请使用sudo执行!" 0

# 统一语言环境
export LANG=en_US.UTF-8
export LANGUAGE=en_US:en

# 获取设备列表
ethlist=$(ifconfig | cut -d\  -f1 | grep -v "lo")

for e in $ethlist
do
    if echo $e | egrep "^e" &> /dev/null
    then
         enp_handle "for" $e
    else
         wlan_handle "for" $e
    fi
    [ $? -eq 0 ] && break
done


